package com.banmajio.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class ShutdownManager implements DisposableBean {

    private final Logger log = LoggerFactory.getLogger(ShutdownManager.class);
    private final ThreadPoolTaskExecutor dataMigrationExecutor;

    @Autowired
    public ShutdownManager(ThreadPoolTaskExecutor dataMigrationExecutor) {
        this.dataMigrationExecutor = dataMigrationExecutor;
    }

    @Override
    public void destroy() throws Exception {
        log.info("开始优雅关闭数据迁移线程池...");
        if (dataMigrationExecutor != null) {
            dataMigrationExecutor.shutdown();
            try {
                if (!dataMigrationExecutor.getThreadPoolExecutor().awaitTermination(60, TimeUnit.SECONDS)) {
                    log.warn("数据迁移线程池关闭超时，尝试强制关闭...");
                    List<Runnable> remainingTasks = dataMigrationExecutor.getThreadPoolExecutor().shutdownNow();
                    log.info("已取消 {} 个未执行的任务", remainingTasks.size());
                }
                log.info("数据迁移线程池已成功关闭");
            } catch (InterruptedException e) {
                log.error("关闭线程池被中断", e);
                Thread.currentThread().interrupt();
            }
        }
    }
}